package com.dx.generator.service;

import com.dx.generator.bean.ConfigDataEntity;
import com.dx.generator.dao.GeneratorDao;
import com.dx.generator.util.GenUtils;
import com.dx.generator.util.PageUtils;
import com.dx.generator.util.Query;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * Description: 代码生成器服务类
 *
 * @author rockstarsteve
 * @version 1.0
 * @copyright Copyright (c) 电信
 * @since 2023/9/7
 */
@Service
public class SysGeneratorService {

    @Autowired
    private GeneratorDao generatorDao;

    /**
     * 查询所有的所有表信息
     * @param query
     * @return
     */
    public PageUtils queryList(Query query) {
        Page<?> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<Map<String, Object>> list = generatorDao.queryList(query);
        PageUtils pageUtils = new PageUtils(list, (int) page.getTotal(), query.getLimit(), query.getPage());
        return pageUtils;
    }

    /**
     * 获取导出的文件数据
     * @param tableNames
     * @param configDataEntity
     * @return
     */
    public byte[] generatorCode(String[] tableNames, ConfigDataEntity configDataEntity) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip, configDataEntity);
        }
        IOUtils.closeQuietly(zip);
        byte[] bytes = outputStream.toByteArray();
        return bytes;
    }

    /**
     * 根据表名查询表的信息
     * @param tableName
     * @return
     */
    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    /**
     * 根据表名查询表的列信息
     * @param tableName
     * @return
     */
    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }
}
